<template>
  <el-dialog v-model="updateDialog" title="员工修改" width="800">
    <el-form :model="formData" ref="formRef" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像" label-width="80">
            <el-upload
                class="avatar-uploader"
                :action="axios.defaults.baseURL+'/file/upload'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"

            >
              <img :src="imageUrl"
                   class="avatar"
                   alt=""/>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="真实姓名" label-width="80" prop="realName">
            <el-input autocomplete="off" v-model="formData.realName"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="密码" label-width="80" prop="password">
            <el-input autocomplete="off" v-model="formData.password"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" label-width="80" prop="gender">
            <el-radio-group v-model="formData.gender">
              <el-radio label="男" :value="1"/>
              <el-radio label="女" :value="0"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证号" label-width="80" prop="idCard">
            <el-input autocomplete="off" v-model="formData.idCard"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" label-width="80" prop="phone">
            <el-input autocomplete="off" v-model="formData.phone"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="出生日期" label-width="80">
            <el-date-picker
                autocomplete="off"
                v-model="formData.dateOfBirth"
                type="date" placeholder="选择日期"
                :editable="false"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属组织" label-width="80" :required="true" style="width: 276px" prop="organizationId">
            <el-tree-select
                autocomplete="off"
                v-model="formData.organizationId"
                placeholder="选择组织"
                :data="organizationList"
                :props="{ children: 'children', label: 'label', value: 'id' }"
                node-key="id"
                label-key="organizationName"
                default-expand-all
                check-strictly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="岗位名称" label-width="80" prop="jobName">
            <el-input autocomplete="off" v-model="formData.jobName"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资" label-width="80">
            <el-input autocomplete="off" v-model="formData.salary"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialog = false">关闭</el-button>
        <el-button @click="save" type="primary">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {defineModel,defineEmits} from "@vue/runtime-core";
import axios from '@/axios/index.js'
import {ElMessage} from "element-plus";
import {Plus} from '@element-plus/icons-vue'
import {UserFilled} from '@element-plus/icons-vue'
import {reactive, ref} from "vue";

let updateDialog = defineModel('updateDialog')
let rowData = defineModel('rowData');
let formData = ref(JSON.parse(JSON.stringify(rowData.value)))
const imageUrl = ref('')
imageUrl.value = formData.value.photoUrl == null?'/src/assets/images/defaultPhoto.png':formData.value.photoUrl
let nan = 1
let nv = 0
const rules = reactive({
  realName: [
    {required: true, message: '请输入名称', trigger: 'blur'},
    {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
  ],
  gender: [
    {required: true, message: '请输入性别', trigger: 'blur'},
  ],
  idCard: [
    {required: true, message: '请输入身份证号', trigger: 'blur'},
    {pattern: '(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)', message: '身份证号格式不正确', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {min: 11, max: 11, message: '输入的号码格式不正确', trigger: 'blur'}
  ],
  organizationId: [
    {required: true, message: '请选择组织', trigger: 'blur'}
  ],
  jobName: [
    {required: true, message: '请输入岗位名称', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ],
})
const formRef = ref(null);
const emit = defineEmits(['updateList'])

//保存用户
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // console.log(formData)
      formData.value.status = formData.value.status ? 1 : 0
      axios.put('/staff', null, {params: formData.value}).then(resp => {
        ElMessage({
          message: resp.data.message,
          type: 'success',
          duration: 1500
        })
        updateDialog.value = false
        emit('updateList',1,5)
      })

    } else {
      return false;
    }
  })
}
// console.log(formData)

const handleAvatarSuccess = (response, uploadFile) => {
  // console.log(uploadFile.raw)
  formData.value.photoUrl = response.data
  imageUrl.value = response.data
  // console.log(formData.value.photoUrl)
}

//上传头像前的处理
const beforeAvatarUpload = (rawFile) => {
  const isJpgOrPng = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('Avatar picture must be JPG or PNG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!');
    return false;
  }
  return true;
}

//获取组织列表
const getOrganizationList = async () => {
  try {
    const response = await axios.get('/organization/getList');
    // console.log(response.data.data)
    return response.data.data.map(item => ({
      id: item.id,
      label: item.organizationName,
      children: item.children ? item.children.map(child => ({
        id: child.id,
        label: child.organizationName
      })) : null
    }));
  } catch (error) {
    console.error('Error fetching organization list:', error);
    return [];
  }
};

let organizationList = ref([]);
(async () => {
  organizationList.value = await getOrganizationList();
  // console.log(organizationList)
})();

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
